namespace('org.mediaconverter');

org.mediaconverter.desktop = Class.extend({
	
	/**
	 * Constructor
	 */
	init: function() {
		
		this.$desktop = $('#desktop');
		
		this.initDock();
		this.initLanguageSelector();
		this.initEvents();
		
		//open the default windows
		if($('#desktop').width() >= 860) {
			$('a.wizard, a.socialmedia, a.news', '#menu').trigger('click');
		}else{
			$('a.wizard', '#menu').trigger('click');
		}
		
	},

	
	/**
	 * Init Dock
	 */
	initDock: function() {
		
		var $dock = $('#menu');
		
		//init dock
		$dock.jqDock();
		
		//load window/layer on item click
		$dock.on('click', 'a', $.proxy(function(ev) {
			ev.preventDefault();
			var $link = $(ev.currentTarget);

			if($link.hasClass('window')) {
				
				$.ajax({
					url: $link.attr('href'),
					success: $.proxy(function(res) {
						//get ID of the window and check if it is not already open
						var windowId = $(res).attr('id');
						var $existingWindow = $('#' + windowId);
						if(!$existingWindow.length) {
							this.$desktop.append(res);
							var $window = $('#' + windowId);
							
							//make it draggable
							$window.draggable({
								handle: '> div.header',
								containment: 'parent',
								stack: '#desktop > div.window'
							});
							
							//fadeIn
							$window.fadeIn(300);
						} else {
							//shake the existing window so the user realizes that it is already open
							$existingWindow.effect('shake', {
								times: 3
							}, 150);
						}
					}, this)
				});
				
			}
			
		}, this));
		
	},
	
	
	/**
	 * Init Language Selector
	 */
	initLanguageSelector: function() {
		
		var $languages = $('#languages');
		$('div.button, div.selection', $languages).click(function(ev) {
			$('div.languages', $languages).slideToggle(300);
		});
		
	},
	
	
	/**
	 * Event listeners
	 */
	initEvents: function() {
		
		$('#desktop').on('click', 'div.window a.close', function(ev) {
			ev.preventDefault();
			$(this).closest('div.window').fadeOut(300, function() {
				$(this).remove();
			});
		});
		
	}
	
});